package com.zhongketech.sunflower;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;

import com.zhongketech.sunflower.adapter.FcsContact;
import com.zhongketech.sunflower.adapter.TextMessageBody;
import com.zhongketech.sunflower.adapter.ZKChatManager;
import com.zhongketech.sunflower.adapter.ZKContact;
import com.zhongketech.sunflower.adapter.ZKGroup;
import com.zhongketech.sunflower.adapter.ZKMessage;
import com.zhongketech.sunflower.adapter.ZKMessage.Type;
import com.zhongketech.sunflower.app.AppManager;
import com.zhongketech.sunflower.sv.SvManager;
import com.zhongketech.sunflower.transport.Action;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.model.DaoMaster;
import com.zhongketech.sunflower.transport.model.MyRequest;
import com.zhongketech.sunflower.transport.model.DaoMaster.OpenHelper;
import com.zhongketech.sunflower.transport.model.DaoSession;
import com.zhongketech.sunflower.transport.model.User;
import com.zhongketech.sunflower.transport.uitl.CustomerHttpClient;
import com.zhongketech.sunflower.utils.ImageCache;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Looper;
import android.os.Message;


public class MyApplication extends Application{

	private static final String TAG = "MyApplication";
	private static MyApplication instance;
	public ImageCache mImageCache;

	private String id = null;
	private String password = null;
	private String phone = null;
	private String visibleId = null;

	private String role = null;
	private String gender;
	private String name;
	private String birthday;
	private String avatar_url;

	private String sessionToken = null;
	private Map<String,String> cookie = null;
	private CookieStore cookieStore = null;

	private Map<String,String> specialNumberWhiteListFamily = null;
	private Map<String,String> specialNumberWhiteListEmergency = null;
	private Map<String,String> specialNumberBlackList = null;

	//for greedao
	private  DaoMaster userDaoMaster;  
	private  DaoSession userDaoSession;
	private  DaoMaster supervisonsDaoMaster;  
	private  DaoSession supervisonsDaoSession;
	private SharedPreferences sharedPreferences;  

	public static MyApplication getInstance() {
		return instance;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		new rootTask().execute();
		instance = this;
		int maxMemorySize = (int) (Runtime.getRuntime().maxMemory() / 4);
		mImageCache = new ImageCache(maxMemorySize);
		initGreedaoDb(this);
		sharedPreferences = getSharedPreferences(Constant.PREFS_NAME, MODE_PRIVATE);
		MyToast.getInstance();
		AppManager.getInstance(); 

	}


	private void initGreedaoDb(Context context)
	{
		if (userDaoMaster == null) 
		{  
			OpenHelper helper = new DaoMaster.DevOpenHelper(context,Constant.USER_DB_NAME, null);  
			userDaoMaster = new DaoMaster(helper.getWritableDatabase());
			setUserDaoSession(userDaoMaster.newSession());  
		}  

		if (supervisonsDaoMaster == null) 
		{  
			//			OpenHelper helper = new DaoMaster.DevOpenHelper(context,Constant.SV_DB_NAME, null);  
			//			supervisonsDaoMaster = new DaoMaster(helper.getWritableDatabase());
			//			setSupervisonsDaoSession(supervisonsDaoMaster.newSession());  

			supervisonsDaoMaster = userDaoMaster;
			supervisonsDaoSession = userDaoSession;
		}  
	}


	public void SetUser(User user)
	{
		if(null != user)
		{
			setAvatar_url(user.getAvatar_url());
			setBirthday(user.getBirthday());
			setGender(user.getGender());
			setId(user.getId());
			setName(user.getName());
			setPassword(user.getPassword());
			setPhone(user.getPhone());
			setRole(user.getRole());
			setVisibleId(user.getVisible_id());
		}
		else
		{
			MyToast.getInstance().show("保存联系人信息出错：联系人为空");
		}

	}

	public User getUser()
	{
		User user = new User();
		user.setAvatar_url(getAvatar_url());
		user.setBirthday(getBirthday());
		user.setGender(getGender());
		user.setId(getId());
		user.setName(getName());
		user.setPassword(getPassword());
		user.setPhone(getPhone());
		user.setRole(getRole());
		user.setVisible_id(getVisibleId());
		return user;
	}


	public String getId() {
		if(null == id)
		{
			id = sharedPreferences.getString(Constant.PREFS_ID, null);
		}

		return id;
	}


	public void setId(String id) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_ID, id);
		editor.commit();
		this.id = id;
	}


	public String getPassword() {
		if(null == password)
		{
			password = sharedPreferences.getString(Constant.PREFS_PW, null); 
		}

		return password;
	}


	public void setPassword(String password) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_PW, password);
		editor.commit();
		this.password = password; 
	}


	public String getPhone() { 

		if(null == phone)
		{
			phone = sharedPreferences.getString(Constant.PREFS_PHONE, null);
		}

		return phone;

	}


	public void setPhone(String phone) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_PHONE, phone);
		editor.commit();
		this.phone = phone;
	}


	public String getVisibleId() {

		if(null == visibleId)
		{
			visibleId = sharedPreferences.getString(Constant.PREFS_VID, null);
		}

		return visibleId;
	}


	public void setVisibleId(String visibleId) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_VID, visibleId);
		editor.commit();

		this.visibleId = visibleId;
	}


	public String getRole() {
		if(null == role)
		{
			role = sharedPreferences.getString(Constant.PREFS_ROLE, null);
		}

		return role;
	}

	public void setRole(String role) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_ROLE, role);
		editor.commit();
		this.role = role;
	}

	public void setSupervisonsDaoSession(DaoSession supervisonsDaoSession) {
		this.supervisonsDaoSession = supervisonsDaoSession;
	}

	public Map<String,String> getSpecialNumberList(String type) {

		Map<String,String> map = null;
		String name = null;
		String phone = null;
		if(Constant.SN_FAMILY.equals(type))
		{
			map = specialNumberWhiteListFamily;
			name = sharedPreferences.getString(Constant.PREFS_SN_NAME_FA, null);
			phone = sharedPreferences.getString(Constant.PREFS_SN_PHONE_FA, null);
		}
		else if(Constant.SN_EMERGENCY.equals(type))
		{
			map = specialNumberWhiteListEmergency;
			name = sharedPreferences.getString(Constant.PREFS_SN_NAME_EM, null);
			phone = sharedPreferences.getString(Constant.PREFS_SN_PHONE_EM, null);
		}
		else
		{
			map = specialNumberBlackList;
			name = sharedPreferences.getString(Constant.PREFS_SN_NAME_BLACK, null);
			phone = sharedPreferences.getString(Constant.PREFS_SN_PHONE_BLACK, null);
		}

		if(null == map)
		{
			LogUtil.i(TAG,"specialNumberGroups type:"+type+" name:"+name+" phone:"+phone);
			if(null != name && null != phone)
			{
				String n[] = name.split(":");
				String p[] = phone.split(":");
				if(null != n && null != p && n.length > 0 && p.length > 0)
				{
					int min = n.length;
					if(min > p.length)
					{
						min = p.length;
					}

					map = new HashMap<String, String>();	
					for(int i = 0;i < min; i ++)
					{
						map.put(n[i], p[i]);
						LogUtil.i(TAG," specialNumberGroups["+i+"]: "+n[i]+" "+ p[i]);
					}
				}
			}

		}

		if(Constant.SN_FAMILY.equals(type))
		{
			specialNumberWhiteListFamily = map;
		}
		else if(Constant.SN_EMERGENCY.equals(type))
		{
			specialNumberWhiteListFamily = map;
		}
		else
		{
			specialNumberBlackList = map;
		}

		return map;
	}

	public void setSpecialNumberList(Map<String,String> specialNumberGroups,String type) {

		if(null != specialNumberGroups && specialNumberGroups.size() > 0)
		{
			final Editor editor =  sharedPreferences.edit();
			final Set set = specialNumberGroups.entrySet();
			final Iterator it = set.iterator();
			Map.Entry mapEntry = (Map.Entry) it.next();
			String name = (String) mapEntry.getKey();
			String phone = (String) mapEntry.getValue();
			while (it.hasNext()) { 
				mapEntry = (Map.Entry) it.next();
				name = name+":"+mapEntry.getKey();
				phone = phone+":"+mapEntry.getValue();
			}

			LogUtil.i(TAG,"setSpecialNumberList type:"+type);
			LogUtil.i(TAG,"setSpecialNumberList name:"+name);
			LogUtil.i(TAG,"setSpecialNumberList phone:"+phone);

			if(Constant.SN_FAMILY.equals(type))
			{
				editor.putString(Constant.PREFS_SN_NAME_FA, name);
				editor.putString(Constant.PREFS_SN_PHONE_FA, phone);
				editor.commit();
				this.specialNumberWhiteListFamily = specialNumberGroups;
			}
			else if(Constant.SN_EMERGENCY.equals(type))
			{
				editor.putString(Constant.PREFS_SN_NAME_EM, name);
				editor.putString(Constant.PREFS_SN_PHONE_EM, phone);
				editor.commit();
				this.specialNumberWhiteListEmergency = specialNumberGroups;
			}
			else
			{
				editor.putString(Constant.PREFS_SN_NAME_BLACK, name);
				editor.putString(Constant.PREFS_SN_PHONE_BLACK, phone);
				editor.commit();
				this.specialNumberBlackList = specialNumberGroups;
			}

		}

	}

	public String getGender() {
		if(null == gender)
		{
			gender = sharedPreferences.getString(Constant.PREFS_GENDER, null);
		}

		return gender;
	}

	public void setGender(String gender) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_GENDER, gender);
		editor.commit();
		this.gender = gender;
	}

	public String getName() {
		if(null == name)
		{
			name = sharedPreferences.getString(Constant.PREFS_USER_NAME, null);
		}

		return name;
	}

	public void setName(String name) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_USER_NAME, name);
		editor.commit();
		this.name = name;
	}

	public String getBirthday() {
		if(null == birthday)
		{
			birthday = sharedPreferences.getString(Constant.PREFS_BIRTHDAY, null);
		}

		return birthday;
	}

	public void setBirthday(String birthday) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_BIRTHDAY, birthday);
		editor.commit();
		this.birthday = birthday;
	}

	public String getAvatar_url() {
		if(null == avatar_url)
		{
			avatar_url = sharedPreferences.getString(Constant.PREFS_AV_URL, null);
		}

		LogUtil.i("ZK","getAvatar_url:"+avatar_url);
		return avatar_url;
	}

	public void setAvatar_url(String avatar_url) {
		final Editor editor =  sharedPreferences.edit();
		String url = avatar_url;
		if(null != url && url.length() > 1 && !url.startsWith("http"))
		{
			url = Constant.IMGAGE_SERVER+url;
		}
		LogUtil.i("ZK","setAvatar_url:"+url);
		editor.putString(Constant.PREFS_AV_URL, url);
		editor.commit();
		this.avatar_url = url;
	}

	public String getSessionToken() {
		if(null == sessionToken)
		{
			sessionToken = sharedPreferences.getString(Constant.PREFS_STK, null);
		}
		return sessionToken;
	}

	public void setSessionToken(String sessionToken) {
		final Editor editor =  sharedPreferences.edit();
		editor.putString(Constant.PREFS_STK, sessionToken);
		editor.commit();

		this.sessionToken = sessionToken;
	}


	public Map<String, String> getCookie() {
		if(null == cookie)
		{
			cookie = new HashMap<String, String>();
			cookie.put(Constant.PREFS_COOKIE_PHPSESSID, sharedPreferences.getString(Constant.PREFS_COOKIE_PHPSESSID, ""));
			cookie.put(Constant.PREFS_COOKIE_ID, sharedPreferences.getString(Constant.PREFS_COOKIE_ID, ""));	
		}

		return cookie;
	}

	public void setCookie(List<Cookie> cookie) {

		final Editor editor =  sharedPreferences.edit();
		if(null == this.cookie)
		{
			this.cookie = new HashMap<String, String>();	
		}
		else
		{
			this.cookie.clear();
		}

		for(int i = 0;i < cookie.size();i ++)
		{
			if(Constant.PREFS_COOKIE_PHPSESSID.equals(cookie.get(i).getName()))
			{
				LogUtil.i(TAG, "PREFS_COOKIE_PHPSESSID:"+cookie.get(i).getValue());
				editor.putString(Constant.PREFS_COOKIE_PHPSESSID, cookie.get(i).getValue());
				this.cookie.put(Constant.PREFS_COOKIE_PHPSESSID, cookie.get(i).getValue());
			}
			else if(Constant.PREFS_COOKIE_ID.equals(cookie.get(i).getName()))
			{
				LogUtil.i(TAG, "PREFS_COOKIE_ID:"+cookie.get(i).getValue());
				editor.putString(Constant.PREFS_COOKIE_ID, cookie.get(i).getValue());
				this.cookie.put(Constant.PREFS_COOKIE_ID, cookie.get(i).getValue());
			}
		}
		editor.commit();
	}

	public CookieStore getCookieStore() {
		return cookieStore;
	}

	public void setCookieStore(CookieStore cookieStore) {
		this.cookieStore = cookieStore;
	}

	/**
	 * 开启线程去获取root权限
	 * 
	 */
	class rootTask extends AsyncTask<String, Object, Integer> 
	{
		private String pkgName = "";

		@Override
		public Integer doInBackground(String... params) {
			Integer result = 1;
			boolean isRoot = com.zhongketech.sunflower.utils.Root.preparesu();
			if(isRoot)
			{
				result = 1;
			}
			else
			{
				result = 0;
			}
			return result;
		}

		@Override
		public void onPostExecute(Integer result) {
			if(1 == result)
			{
				LogUtil.i(TAG, "已获取ROOT权限");
			}
			else
			{
				LogUtil.i(TAG, "获取ROOT权限失败");
			}

			super.onPostExecute(result);
		}

	}


	/**
	 * all test code,add data
	 */

	List<ZKContact> resultList = null;
	public List<ZKContact> getChatList() {

		if(null != resultList)
		{
			return resultList;
		}

		resultList = new ArrayList<ZKContact>();

		ZKContact contact = new ZKContact("入校通知",null,R.drawable.in_school);
		resultList.add(contact);
		LogUtil.i(TAG, "contact id:"+contact.getId());
		TextMessageBody body = new TextMessageBody("你孩子7：00到达学校");
		ZKMessage message = new ZKMessage("7:00", Type.TXT, body);
		ZKChatManager.getInstance().addConversation(contact.getId(),"入校通知", message);


		ZKContact contact1 = new ZKContact("离校通知",null,R.drawable.leave_school);
		resultList.add(contact1);
		LogUtil.i(TAG, "contact id:"+contact1.getId());
		TextMessageBody body1 = new TextMessageBody("你孩子17：00离开学校");
		ZKMessage message1 = new ZKMessage("17:00", Type.TXT, body1);
		ZKChatManager.getInstance().addConversation(contact1.getId(),"离校通知", message1);

		ZKContact contact2 = new ZKContact("学校通知",null,R.drawable.school);
		resultList.add(contact2);
		LogUtil.i(TAG, "contact id:"+contact2.getId());
		TextMessageBody body2 = new TextMessageBody("快乐的暑假即将来临...");
		ZKMessage message2 = new ZKMessage("昨天", Type.TXT, body2);
		ZKChatManager.getInstance().addConversation(contact2.getId(),"学校通知", message2);

		ZKContact contact3 = new ZKContact("班级通知",null,R.drawable.class_group);
		resultList.add(contact3);
		LogUtil.i(TAG, "contact id:"+contact3.getId());
		TextMessageBody body3 = new TextMessageBody("快乐的暑假即将来临...");
		ZKMessage message3 = new ZKMessage("昨天", Type.TXT, body3);
		ZKChatManager.getInstance().addConversation(contact3.getId(),"班级通知", message3);

		ZKContact contact4 = new ZKContact("李同学",null,null);
		resultList.add(contact4);
		LogUtil.i(TAG, "contact4 id:"+contact4.getId());
		TextMessageBody body4 = new TextMessageBody("放假了，准备去哪玩？");
		ZKMessage message4 = new ZKMessage("星期五", Type.TXT, body4);
		ZKChatManager.getInstance().addConversation(contact4.getId(),"李同学", message4);
		ZKChatManager.getInstance().getConversation(contact4.getId()).setUnreadMsgCount(2);

		ZKContact ZKGroup =  new ZKGroup("家里人",null,null);
		resultList.add((ZKContact)ZKGroup);
		TextMessageBody body5 = new TextMessageBody("姑姑：今晚过来吃饭吧");
		ZKMessage message5 = new ZKMessage("昨晚", Type.TXT, body5);
		ZKChatManager.getInstance().addConversation(ZKGroup.getId(),"家里人", message5);
		ZKChatManager.getInstance().getConversation(ZKGroup.getId()).setUnreadMsgCount(5);
		/*test code end*/

		return resultList;
	}


	public Map<String, User> getContactList() {

		Map<String, User> userMap = new HashMap<String, User>();
		//		ZKContact contact5 = new ZKContact(Constant.NEW_FRIENDS_USERNAME,null,null);
		//		ZKContact contact6 = new ZKContact(Constant.GROUP_USERNAME,null,null);
		//		ZKContact contact = new ZKContact("李同学",null,R.drawable.in_school);
		//		ZKContact contact1 = new ZKContact("同学李",null,R.drawable.leave_school);
		//		ZKContact contact2 = new ZKContact("小毛",null,R.drawable.school);
		//		ZKContact contact3 = new ZKContact("妈妈",null,R.drawable.class_group);
		//		ZKContact contact4 = new ZKContact("爸爸",null,null);
		//
		//		userMap.put(contact5.getNick() != null ? contact5.getNick() : contact5.getUsername(), contact5);
		//		userMap.put(contact6.getNick() != null ? contact6.getNick() : contact6.getUsername(), contact6);
		//		userMap.put(contact.getNick() != null ? contact.getNick() : contact.getUsername(), contact);
		//		userMap.put(contact1.getNick() != null ? contact1.getNick() : contact1.getUsername(), contact1);
		//		userMap.put(contact2.getNick() != null ? contact2.getNick() : contact2.getUsername(), contact2);
		//		userMap.put(contact3.getNick() != null ? contact3.getNick() : contact.getUsername(), contact3);
		//		userMap.put(contact4.getNick() != null ? contact4.getNick() : contact4.getUsername(), contact4);

		return userMap;
	}

	public DaoMaster getUserDaoMaster() {
		return userDaoMaster;
	}



	public DaoMaster getSupervisonsDaoMaster() {
		return supervisonsDaoMaster;
	}



	public DaoSession getUserDaoSession() {
		return userDaoSession;
	}

	public void setUserDaoSession(DaoSession userDaoSession) {
		this.userDaoSession = userDaoSession;
	}

	public DaoSession getSupervisonsDaoSession() {
		return supervisonsDaoSession;
	}
}
